package net.wofly.right.web;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.wofly.right.domain.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.wofly.common.persistence.PageWrapper;
import net.wofly.common.util.ReturnBean;
import net.wofly.common.web.BaseController;
import net.wofly.right.dto.CustomDto;
import net.wofly.right.service.ICustomerService;
import net.wofly.right.service.IOrganizationService;
import net.wofly.right.service.IRightConfigService;
import net.wofly.right.service.IRightService;
import net.wofly.right.service.IUserReceivingAddrService;
import net.wofly.right.service.IUserService;
import net.wofly.right.shiro.ShiroService;
import net.wofly.right.validator.RightValidator;
import net.wofly.right.validator.UserValidator;

@Controller
@RequestMapping(value = "/api/right")
@Api(description = "权限接口")
public class RightController extends BaseController{

    private static final Logger logger = LoggerFactory.getLogger(RightController.class);

    @Resource
    ShiroService shiroService;

    @Resource
    IRightService iRightService;
    
    @Resource
    IUserService iUserService;
    
    @Resource
    IOrganizationService iOrganizationService;

    @Resource
    IRightConfigService iRightConfigService;
    
    @Resource
    IUserReceivingAddrService iUserReceivingAddrService ;
    
    @Resource
    ICustomerService iCustomerService ;
    
    /**
     * 添加员工
     *
     * @param user
     */
    @ApiOperation(value = "添加员工", notes = "添加员工")
    @ApiImplicitParam(name = "user", value = "员工实体", required = true, dataType = "User")
    @RequestMapping(value = "/addUser", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<User> addUser(@RequestBody User user) {
        ReturnBean<User> returnBean;
        String errorMessage = RightValidator.validateAddUserParams(user);
        if (StringUtils.isNotEmpty(errorMessage)) {
            returnBean = new ReturnBean<User>(1, errorMessage);
        } else {
            returnBean = iRightService.addUser(user);
        }
        return returnBean;
    }
    
    /**
     * 添加组织机构
     * <ul>
     * <li>添加组织机构时，如果组织机构有仓库，则在仓库表中自动为组织机构创建仓库，并将仓库ID回写到组织机构表中</li>
     * </ul>
     *
     * @param organization
     */
    @ApiOperation(value = "添加组织机构", notes = "添加组织机构")
    @ApiImplicitParam(name = "organization", value = "组织机构实体", required = true, dataType = "Organization")
    @RequestMapping(value = "/addOrganization", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<Organization> addOrganization(@RequestBody Organization organization) {
        ReturnBean<Organization> returnBean;
        String errorMessage = RightValidator.validateAddOrganizationParams(organization);
        if (StringUtils.isNotEmpty(errorMessage)) {
            returnBean = new ReturnBean<Organization>(1, errorMessage);
        } else {
            returnBean = iRightService.addOrganization(organization);
        }
        return returnBean;
    }
    
    /**
     * 删除员工
     * <ul>
     * <li>将员工置为无效</li>
     * </ul>
     *
     * @param userID
     */
    @ApiOperation(value = "删除员工", notes = "删除员工")
    @ApiImplicitParam(name = "userID", value = "员工ID", required = true, dataType = "String", paramType = "form")
    @RequestMapping(value = "/delUser", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<User> delUser(@RequestParam(required = true) String userID) {
        if (StringUtils.isEmpty(userID)) {
            return new ReturnBean<User>(1, "userID不能为空");
        }
        return iRightService.delUser(userID);
    }
    
    /**
     * 删除组织机构
     * <ul>
     * <li>将组织机构置为无效。</li>
     * <li>如果有仓库也置为无效</li>
     * <li></li>
     * </ul>
     *
     * @param organizationID
     */
    @ApiOperation(value = "删除组织机构", notes = "根据组织机构ID删除组织机构")
    @ApiImplicitParam(name = "organizationID", value = "组织机构ID", required = true, dataType = "String", paramType = "form")
    @RequestMapping(value = "/delOrganization", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<String> delOrganization(String organizationID) {
        if (StringUtils.isEmpty(organizationID)) {
            return new ReturnBean<String>(1, "organizationID不能为空");
        }
        return iRightService.delOrganization(organizationID);
    }
    
    /**
     * 获取所有员工
     * <ul>
     * <li>flag=1　获取有效的员工</li>
     * <li>flag=0　获取无效的员工</li>
     * <li>flag=-1　获取所有的员工</li>
     * </ul>
     *
     * @param flag
     */
    @ApiOperation(value = "获取所有员工信息", notes = "获取所有员工信息")
    @ApiImplicitParam(name = "flag", value = "flag标识(flag默认为1,查所有有效员工，flag=1　获取有效的员工,flag=0　获取无效的员工," +
            "flag=-1　获取所有的员工)", required = false, dataType = "Integer", paramType = "form")
    @RequestMapping(value = "/getAllUser", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<PageWrapper<User>> getAllUser(@Param(value = "1") Integer flag, Integer pageNum,
                                                            Integer pageSize) {
        return iRightService.getAllUser(flag, pageNum, pageSize);
    }
    
    /**
     * 获取所有组织机构
     * <ul>
     * <li>flag=1时，只取所有有效的组织机构；flag=0时，只取所有无效的组织机构，flag=-1返回所有组织机构</li>
     * <li>排列机构的父子关系</li>
     * <li></li>
     * </ul>
     *
     * @param flag
     */
    @ApiOperation(value = "获取所有组织机构", notes = "获取所有组织机构")
    @ApiImplicitParam(name = "flag", value = "flag标识(flag=1时，只取所有有效的组织机构；flag=0时，只取所有无效的组织机构，flag=-1返回所有组织机构)",
            required = false, dataType = "Integer", paramType = "form")
    @RequestMapping(value = "/getAllOrganization", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<List<Organization>> getAllOrganization(@Param(value = "1") Integer flag) {
        return iRightService.getAllOrganization(flag);
    }
    
    /**
     * 获取所有员工
     * <ul>
     * <li>flag=1　获取有效的员工</li>
     * <li>flag=0　获取无效的员工</li>
     * <li>flag=-1　获取所有的员工</li>
     * </ul>
     *
     * @param organizationID
     */
    @ApiOperation(value = "根据机构ID获取所有员工", notes = "根据机构ID获取所有员工")
    @ApiImplicitParams({@ApiImplicitParam(name = "organizationID", value = "机构ID", required = true, dataType =
            "String", paramType = "form"), @ApiImplicitParam(name = "flag", value = "flag标识(flag默认为1,查所有有效员工，flag=1　获取有效的员工," +
            "flag=0　获取无效的员工,flag=-1　获取所有的员工)", required = false, dataType = "Integer", paramType = "form")})
    @RequestMapping(value = "/getUserByOrganization", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<List<User>> getUserByOrganization(String organizationID, Integer flag) {
        ReturnBean<List<User>> returnBean;
        String errorMessage = RightValidator.validateGetUserByOrganizationParams(organizationID);
        if (errorMessage.length() > 0) {
            returnBean = new ReturnBean<List<User>>(1, errorMessage);
        } else {
            returnBean = iRightService.getUserByOrganization(organizationID, flag);
        }
        return returnBean;
    }
    
    /**
     * 根据角色ID获取用户
     * <ul>
     * <li></li>
     * </ul>
     *
     * @param roleID
     */
    @ApiOperation(value = "根据角色ID获取用户", notes = "根据角色ID获取用户")
    @ApiImplicitParam(name = "roleID", value = "角色ID", required = true, dataType = "String", paramType = "form")
    @RequestMapping(value = "/getUserByRole", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<List<User>> getUserByRole(String roleID) {
        if (StringUtils.isEmpty(roleID)) {
            return new ReturnBean<List<User>>(1, "roleID不能为空");
        }
        return iRightService.getUserByRole(roleID);
    }
    
    /**
     * 获取业务经理及店员列表
     * <ul>
     * <li></li>
     * </ul>
     *
     * @param roleID
     */
    @ApiOperation(value = "获取业务经理及店员列表", notes = "获取业务经理及店员列表")
    @RequestMapping(value = "/getBussManagerAndClerk", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<List<User>> getBussManagerAndClerk() {
        
        return iRightService.getBussManagerAndClerk() ;
    }
    
    /**
     * 获取员工角色列表
     *
     * @param userID
     */
    @ApiOperation(value = "获取员工角色列表", notes = "获取员工角色列表")
    @ApiImplicitParam(name = "userID", value = "员工ID", required = true, dataType = "String", paramType = "form")
    @RequestMapping(value = "/getUserRole", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<List<Role>> getUserRole(String userID) {
        if (StringUtils.isEmpty(userID)) {
            return new ReturnBean<List<Role>>(1, "userID不能为空");
        }
        return iRightService.getUserRole(userID);
    }
    
    /**
     * @param userRole
     */
    @ApiOperation(value = "设置员工角色", notes = "设置员工角色")
    @ApiImplicitParam(name = "userRole", value = "员工-角色对应关系", required = true, dataType = "UserRole")
    @RequestMapping(value = "/setUserRole", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<String> setUserRole(@RequestBody UserRole userRole) {
        ReturnBean<String> returnBean;
        String errorMessage = RightValidator.validateSetUserRoleParams(userRole);
        if (StringUtils.isNotEmpty(errorMessage)) {
            returnBean = new ReturnBean<String>(1, errorMessage);
        } else {
            returnBean = iRightService.setUserRole(userRole);
        }
        return returnBean;
    }
    
    /**
     * 修改员工
     * <ul>
     * <li></li>
     * </ul>
     *
     * @param user
     */
    @ApiOperation(value = "修改员工信息", notes = "修改员工信息")
    @ApiImplicitParam(name = "user", value = "员工信息", required = true, dataType = "User")
    @RequestMapping(value = "/updateUser", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<User> updateUser(@RequestBody User user) {
        ReturnBean<User> returnBean;
        String errorMessage = RightValidator.validateUpdateUserParams(user);
        if (StringUtils.isNotEmpty(errorMessage)) {
            returnBean = new ReturnBean<User>(1, errorMessage);
        } else {
            returnBean = iRightService.updateUser(user);
        }
        return returnBean;
    }
    
    /**
     * 更新组织机构
     * <ul>
     * <li>如果以前组织机构没有仓库可以修改为有仓库，自动在仓库中为组织机构生成仓库，并将仓库ID回写到组织机构表中</li>
     * <li>如果以前组织机构有仓库则不可以修改为无仓库。或其它仓库类型</li>
     * <li></li>
     * </ul>
     *
     * @param organization
     */
    @ApiOperation(value = "更新组织机构信息", notes = "更新组织机构信息")
    @ApiImplicitParam(name = "organization", value = "组织机构信息", required = true, dataType = "Organization")
    @RequestMapping(value = "/updateOrganization", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<Organization> updateOrganization(@RequestBody Organization organization) {
        ReturnBean<Organization> returnBean;
        String errorMessage = RightValidator.validateUpdateOrganizationParams(organization);
        if (StringUtils.isNotEmpty(errorMessage)) {
            returnBean = new ReturnBean<Organization>(1, errorMessage);
        } else {
            returnBean = iRightService.updateOrganization(organization);
        }
        return returnBean;
    }


    /**
     * 登陆
     * <ul>
     * <li>目前只有手机，可以支持根据帐号来判断登陆帐号类型</li>
     * <li>前后交互时，密码加密处理</li>
     * </ul>
     *
     * @param accountID
     * @param password
     */
    @RequiresRoles("admin")
    @RequiresPermissions(value = {"/api/right/updateInitPermission"})
    @ApiOperation(value = "初始过滤权限更新")
    @ApiImplicitParams({@ApiImplicitParam(name = "accountID", value = "手机号码或者邮箱", required = true, dataType = "String", paramType = "form"),
                               @ApiImplicitParam(name = "password", value = "密码（加密传输）", required = true, dataType = "String", paramType = "form")})
    @RequestMapping(value = "/updateInitPermission", method = {RequestMethod.GET})
    @ResponseBody
    public ReturnBean<String> updateInitPermission(String accountID, String password) {
        ReturnBean<String> returnBean;
        String errorMessage = UserValidator.validateLoginParams(accountID, password);
        if (errorMessage.length() > 0) {
            returnBean = new ReturnBean<String>(-1, errorMessage);
        } else {
            shiroService.updateInitPermission();
            returnBean = new ReturnBean<String>(0,"更新成功");
        }
        return returnBean;
    }
    
    //@RequiresPermissions(value = {"/api/right/addCompanyCustomer"})
    @ApiOperation(value = "添加企业客户", notes = "添加企业客户")
    @ApiImplicitParams({@ApiImplicitParam(name = "organization", value = "企业客户信息", required = true, dataType = "Organization", paramType = "body")})
    @RequestMapping(value = "/addCompanyCustomer", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<Organization> addCompanyCustomer(@RequestBody Organization organization) {
        ReturnBean<Organization> returnBean;
        
        String errorMessage = UserValidator.validateAddCustomParams(organization);
        if (errorMessage.length() > 0) {
            returnBean = new ReturnBean<Organization>(-1, errorMessage);
        } else {
            returnBean = iOrganizationService.addCompanyCustomer(organization) ;
        }
        return returnBean;
    }
    
    //@RequiresPermissions(value = {"/api/right/saveCustomer"})
    @ApiOperation(value = "添加客户", notes = "添加客户")
    @ApiImplicitParams({@ApiImplicitParam(name = "customDto", value = "客户信息", required = true, dataType = "CustomDto", paramType = "body")})
    @RequestMapping(value = "/saveCustomer", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<String> saveCustomer(@RequestBody CustomDto customDto) {
        ReturnBean<String> returnBean;
        
        String errorMessage = UserValidator.validateSaveCustomParams(customDto) ;
        if (errorMessage.length() > 0) {
            returnBean = new ReturnBean<>(-1, errorMessage);
        } else {
            returnBean = iOrganizationService.saveCustomer(customDto);
        }
        return returnBean;
    }
    
    //@RequiresPermissions(value = {"/api/right/getCustomer"})
    @ApiOperation(value = "获取客户详情", notes = "获取客户详情")
    @ApiImplicitParams({@ApiImplicitParam(name = "organizationID", value = "客户ID", required = true, dataType = "String", paramType = "form")})
    @RequestMapping(value = "/getCustomer", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<User> getCustomer(String userID) {
        ReturnBean<User> returnBean;
        
        String errorMessage = UserValidator.validateGetCustomParams(userID);
        if (errorMessage.length() > 0) {
            returnBean = new ReturnBean<User>(-1, errorMessage);
        } else {
            returnBean = iOrganizationService.getCustomer(userID) ;
        }
        return returnBean;
    }
    
    //@RequiresPermissions(value = {"/api/right/getCustomerDto"})
    @ApiOperation(value = "获取客户详情", notes = "获取客户详情")
    @ApiImplicitParams({@ApiImplicitParam(name = "customUserID", value = "客户ID", required = true, dataType = "String", paramType = "form")})
    @RequestMapping(value = "/getCustomerDto", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<CustomDto> getCustomerDto(String customUserID) {
        ReturnBean<CustomDto> returnBean;
        
        String errorMessage = UserValidator.validateGetCustomParams(customUserID);
        if (errorMessage.length() > 0) {
            returnBean = new ReturnBean<>(-1, errorMessage);
        } else {
            returnBean = iOrganizationService.getCustomerDto(customUserID) ;
        }
        return returnBean;
    }
    
    //@RequiresPermissions(value = {"/api/right/getCustomerByCondition"})
    @ApiOperation(value = "客户高级查询", notes = "客户高级查询")
    @ApiImplicitParams({@ApiImplicitParam(name = "organizationName", value = "组织机构名称", required = true, dataType = "String", paramType = "form")})
    @RequestMapping(value = "/getCustomerByCondition", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<Organization> getCustomerByCondition(String organizationName, String mobile, String customType, String followUserID, Integer pageNum, Integer pageSize) {
    	
        ReturnBean<Organization> returnBean ;
        
        
        return null ;
    }

    /**
     * 修改手机号
     * <ol>
     * 	<li>第一步是通过新手机号发送验证码。与注册发送验证码共同接口。</li>
     * 	<li>第二步，验证当前用户密码是否正确。</li>
     * 	<li>再验证手机号是否己注册</li>
     * 	<li>最后验证手机及手机验证码。都正确后，新当前用户手机号改为新手机号</li>
     * </ol>
     *
     * @param userID
     * @param pwd
     * @param newMobile
     * @param verifyCode
     */
    @ApiOperation(value = "修改手机号接口")
    @ApiImplicitParams({@ApiImplicitParam(name = "userID", value = "用户ID", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "pwd", value = "密码", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "newMobile", value = "新手机号", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "verifyCode", value = "验证码", required = true, dataType = "String", paramType = "form")
    })
    @RequestMapping(value = "/changeMobile", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<String> changeMobile(String userID, String pwd, String newMobile, String verifyCode){
        ReturnBean<String> returnBean;
        String errorMessage = UserValidator.validateChangeMobileParams(userID, pwd, newMobile, verifyCode);
        if (errorMessage.length() > 0) {
            returnBean = new ReturnBean<>(-1, errorMessage);
        } else {
            returnBean = iRightService.changeMobile(userID, pwd, newMobile, verifyCode);
        }
        return returnBean;
    }

    /**
     * 通过手机，找回密码
     * <ol>
     * 	<li>第一步是通过手机号发送验证码，可以与手机注册共用一个接口</li>
     * 	<li>当前接口是第二步，通过手机号，验证码，设置新密码。</li>
     * 	<li>验证手机号与验证码有效，且在有效时间内，提示用户新密码修改成功</li>
     * </ol>
     *
     * @param mobile
     * @param verifyCode
     * @param newPwd
     */
    @ApiOperation(value = "通过手机，找回密码接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", value = "手机号", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "verifyCode", value = "验证码", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "newPwd", value = "新密码", required = true, dataType = "String", paramType = "form")
    })
    @RequestMapping(value = "/findPwdByMobile", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<String> findPwdByMobile(String mobile, String verifyCode, String newPwd){
        ReturnBean<String> returnBean;
        String errorMessage = UserValidator.validateFindPwdByMobileParams(mobile, verifyCode, newPwd);
        if (errorMessage.length() > 0) {
            returnBean = new ReturnBean<>(-1, errorMessage);
        } else {
            returnBean = iRightService.findPwdByMobile(mobile, verifyCode, newPwd);
        }
        return returnBean;
    }

    /**
     * 获取用户信息
     * <ol>
     * 	<li>包括头像路径</li>
     * </ol>
     *
     * @param userID
     */
    @ApiOperation(value = "获取用户信息")
    @ApiImplicitParams({@ApiImplicitParam(name = "userID", value = "用户ID", required = true, dataType = "String", paramType = "form")
    })
    @RequestMapping(value = "/getUser", method = {RequestMethod.GET})
    @ResponseBody
    public ReturnBean<User> getUser(String userID){
        ReturnBean<User> returnBean;
        String errorMessage = UserValidator.validateGetUserParams(userID);
        if (errorMessage.length() > 0) {
            returnBean = new ReturnBean<>(-1, errorMessage);
        } else {
            returnBean = iRightService.getUser(userID);
        }
        return returnBean;
    }

    /**
     * 修改密码
     * <ol>
     * 	<li>通过旧密码修改为新密码。旧密码通过验证后，将新密码保存</li>
     * 	<li></li>
     * </ol>
     *
     * @param userID
     * @param oldPwd
     * @param newPwd
     */
    @ApiOperation(value = "修改密码接口")
    @ApiImplicitParams({@ApiImplicitParam(name = "userID", value = "用户ID", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "oldPwd", value = "旧密码", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "newPwd", value = "新密码", required = true, dataType = "String", paramType = "form")
    })
    @RequestMapping(value = "/modifyPwd", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<String> modifyPwd(String userID, String oldPwd, String newPwd){
        ReturnBean<String> returnBean;
        String errorMessage = UserValidator.validateModifyPwdParams(userID, oldPwd, newPwd);
        if (errorMessage.length() > 0) {
            returnBean = new ReturnBean<>(-1, errorMessage);
        } else {
            returnBean = iRightService.modifyPwd(userID, oldPwd, newPwd);
        }
        return returnBean;
    }

    /**
     * 设置用户昵称与性别
     * <ol>
     * 	<li>昵称存User表name字段中。</li>
     * 	<li>性别：男为1，女为0.默认为-1</li>
     * </ol>
     *
     * @param userID
     * @param nickName
     * @param sex
     */
    @ApiOperation(value = "设置用户昵称与性别接口")
    @ApiImplicitParams({@ApiImplicitParam(name = "userID", value = "用户ID", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "nickName", value = "昵称", required = false, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "sex", value = "性别", required = false, dataType = "int", paramType = "form")
    })
    @RequestMapping(value = "/setUserNickName", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<String> setUserNickName(String userID, String nickName, Integer sex){
        ReturnBean<String> returnBean;
        String errorMessage = UserValidator.validateSetUserNickNameParams(userID, nickName, sex);
        if (errorMessage.length() > 0) {
            returnBean = new ReturnBean<>(-1, errorMessage);
        } else {
            returnBean = iRightService.setUserNickName(userID, nickName, sex);
        }
        return returnBean;
    }

    /**
     * 上传用户头像
     * <ol>
     * 	<li>上传用户头像到指定位置</li>
     * 	<li>这个接口根据实际情况来改</li>
     * 	<li></li>
     * </ol>
     *
     * @param userID
     * @param headPic
     */
    @ApiOperation(value = "上传用户头像接口")
    @ApiImplicitParams({@ApiImplicitParam(name = "userID", value = "用户ID", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "headPic", value = "头像文件", required = true, dataType = "MultipartFile", paramType = "form")
    })
    @RequestMapping(value = "/uploadUserHeadPic", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<String> uploadUserHeadPic(String userID, MultipartFile headPic, HttpServletRequest request){
        ReturnBean<String> returnBean;
        String errorMessage = UserValidator.validateUploadUserHeadPicParams(userID, headPic);
        if (errorMessage.length() > 0) {
            returnBean = new ReturnBean<>(-1, errorMessage);
        } else {
            String path = request.getSession().getServletContext().getRealPath("/");
            returnBean = iRightService.uploadUserHeadPic(userID, headPic, path);
        }
        return returnBean;
    }
    
    @ApiOperation(value = "获取所有门店")
    @RequestMapping(value = "/getAllShop", method = {RequestMethod.GET})
    @ResponseBody
    public ReturnBean<List<Organization>> getAllShop() {
        ReturnBean<List<Organization>>  returnBean = iRightService.getAllShop();
        return returnBean;
    }
    
    /**
     * 获取提定员工的维护客户
     * 
     * 针对销售
     *
     * @param salesUserID
     * @param customName
     * @param linkMan
     * @param mobile
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "获取我的客户")
    @ApiImplicitParams({@ApiImplicitParam(name = "salesUserID", value = "员工ID", required = true, dataType = "String", paramType = "form") ,
    		@ApiImplicitParam(name = "customName", value = "客户名称", required = false, dataType = "String", paramType = "form"),
        @ApiImplicitParam(name = "linkMan", value = "联系人", required = false, dataType = "String", paramType = "form"),
        @ApiImplicitParam(name = "mobile", value = "联系电话", required = false, dataType = "String", paramType = "form"),
        @ApiImplicitParam(name = "organizationType", value = "客户类型", required = false, dataType = "String", paramType = "form"),
        @ApiImplicitParam(name = "pageNum", value = "页码（默认第一页）", required = true, dataType = "String", paramType = "form"),
        @ApiImplicitParam(name = "pageSize", value = "每页显示条数（默认10条）", required = true, dataType = "String", paramType = "form")})
    @RequestMapping(value = "/getMyCustomDto", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<PageWrapper<Organization>> getMyCustomDto(String salesUserID, String customName , String linkMan ,String mobile ,String organizationType ,
    			@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10")Integer pageSize) {
    		if (StringUtils.isEmpty(salesUserID)) {
    			salesUserID = "" ;
		}
    		if (StringUtils.isEmpty(customName)) {
			customName = "" ;
		}
		if (StringUtils.isEmpty(linkMan)) {
			linkMan = "" ;
		}
		if (StringUtils.isEmpty(mobile)) {
			mobile = "" ;
		}
        ReturnBean<PageWrapper<Organization>>  returnBean =  iOrganizationService.findMyCustomerByPage(salesUserID, customName, linkMan, mobile ,organizationType, pageNum, pageSize) ;
        return returnBean;
    }
    
    /**
     * 获取所有客户
     *
     * @param customName
     * @param linkMan
     * @param mobile
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "获取所有客户")
    @ApiImplicitParams({@ApiImplicitParam(name = "customName", value = "客户名称", required = false, dataType = "String", paramType = "form"),
	    @ApiImplicitParam(name = "linkMan", value = "联系人", required = false, dataType = "String", paramType = "form"),
	    @ApiImplicitParam(name = "mobile", value = "联系电话", required = false, dataType = "String", paramType = "form"),
	    @ApiImplicitParam(name = "organizationType", value = "客户类型", required = false, dataType = "String", paramType = "form"),
	    @ApiImplicitParam(name = "pageNum", value = "页码（默认第一页）", required = true, dataType = "String", paramType = "form"),
	    @ApiImplicitParam(name = "pageSize", value = "每页显示条数（默认10条）", required = true, dataType = "String", paramType = "form")})
    @RequestMapping(value = "/getAllCustomDto", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<PageWrapper<Organization>> getAllCustomDto(String customName , String linkMan ,String mobile ,String organizationType,
    			@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10")Integer pageSize) {
    		
    		if (StringUtils.isEmpty(customName)) {
    			customName = "" ;
    		}
    		if (StringUtils.isEmpty(linkMan)) {
    			linkMan = "" ;
    		}
    		if (StringUtils.isEmpty(mobile)) {
    			mobile = "" ;
    		}
    		
    		ReturnBean<PageWrapper<Organization>>  returnBean =  iOrganizationService.findAllCustomerByPage(customName, linkMan, mobile,organizationType, pageNum, pageSize) ;
        return returnBean;
    }

    @ApiOperation(value = "导出所有客户")
    @RequestMapping(value = "/export2007AllCustomDto", method = RequestMethod.GET)
    public void export2007AllCustomDto(HttpServletRequest request, HttpServletResponse response) {
        ReturnBean<PageWrapper<Organization>>  returnBean =  iOrganizationService.findAllCustomerByPage("", "", "", "", 1, 20000) ;
        List<Organization> organizations =  returnBean.getResult() != null ? returnBean.getResult().getContent() : new ArrayList<>();

        XSSFWorkbook wb;
        try {
            String basePath = ResourceUtils.getURL("classpath:").getPath();
            // excel模板路径
            String excel = basePath + "/static/excel/customer.xlsx";
            File fi = new File(excel);
            // 读取excel模板
            wb = new XSSFWorkbook(new FileInputStream(fi));
            // 读取了模板内所有sheet内容
            XSSFSheet sheet = wb.getSheetAt(0);
            // 在相应的单元格进行赋值
            int rowIndex = 2;
            for (Organization organization : organizations) {
                XSSFRow row = sheet.getRow(rowIndex);
                if (null == row) {
                    row = sheet.createRow(rowIndex);
                }
                addCellValueForString(row, 0, organization.getOrganizationName());
                addCellValueForString(row, 1, organization.getOrganizationTypeStr());
                addCellValueForString(row, 2, organization.getAddr());
                addCellValueForString(row, 3, organization.getLinkman());
                addCellValueForString(row, 4, organization.getMobile());

                CustomInfo customInfo = organization.getCustomInfo();

                if (customInfo != null) {
                    addCellValueForString(row, 5, customInfo.getBusinessArea());
                    addCellValueForString(row, 6, customInfo.getCustomerLevel());
                    addCellValueForInteger(row, 7, customInfo.getDiningTable());
                    addCellValueForInteger(row, 8, customInfo.getCassetteDeck());
                    addCellValueForInteger(row, 9, customInfo.getBigBox());
                    addCellValueForInteger(row, 10, customInfo.getMidBox());
                    addCellValueForInteger(row, 11, customInfo.getMinBox());
                    addCellValueForString(row, 12, customInfo.getCurrCooperationSituation());
                    addCellValueForIntegerStatus(row, 13, customInfo.getFive());
                    addCellValueForIntegerStatus(row, 14, customInfo.getSix());
                    addCellValueForIntegerStatus(row, 15, customInfo.getTen());
                    addCellValueForIntegerStatus(row, 16, customInfo.getTwenty());
                    addCellValueForIntegerStatus(row, 17, customInfo.getRedBeautiful());
                    addCellValueForIntegerStatus(row, 18, customInfo.getSilverBeautiful());
                    addCellValueForIntegerStatus(row, 19, customInfo.getRemark1());
                    addCellValueForIntegerStatus(row, 20, customInfo.getRemark2());
                    addCellValueForIntegerStatus(row, 21, customInfo.getRemark3());
                    addCellValueForIntegerStatus(row, 22, customInfo.getRemark4());
                    addCellValueForString(row, 23, customInfo.getCompetitorCooperationForm());
                    addCellValueForString(row, 24, customInfo.getCompetitorProductAndPrise());
                    addCellValueForString(row, 25, customInfo.getDescp());
                } else {
                    addCellValueForString(row, 5, "");
                    addCellValueForString(row, 6, "");
                    addCellValueForInteger(row, 7, 0);
                    addCellValueForInteger(row, 8, 0);
                    addCellValueForInteger(row, 9, 0);
                    addCellValueForInteger(row, 10, 0);
                    addCellValueForInteger(row, 11, 0);
                    addCellValueForString(row, 12, "");
                    addCellValueForIntegerStatus(row, 13, 0);
                    addCellValueForIntegerStatus(row, 14, 0);
                    addCellValueForIntegerStatus(row, 15, 0);
                    addCellValueForIntegerStatus(row, 16, 0);
                    addCellValueForIntegerStatus(row, 17, 0);
                    addCellValueForIntegerStatus(row, 18, 0);
                    addCellValueForIntegerStatus(row, 19, 0);
                    addCellValueForIntegerStatus(row, 20, 0);
                    addCellValueForIntegerStatus(row, 21, 0);
                    addCellValueForIntegerStatus(row, 22, 0);
                    addCellValueForString(row, 23, "");
                    addCellValueForString(row, 24, "");
                    addCellValueForString(row, 25, "");
                }

                addCellValueForString(row, 26, organization.getFollowUser() == null ? null : organization.getFollowUser().getName());

                rowIndex++;
            }

            String fileName = "客户列表";
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            wb.write(os);
            byte[] content = os.toByteArray();
            InputStream is = new ByteArrayInputStream(content);
            // 设置response参数，可以打开下载页面
            response.reset();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xlsx").getBytes(), "iso-8859-1"));
            ServletOutputStream sout = response.getOutputStream();
            BufferedInputStream bis = null;
            BufferedOutputStream bos = null;

            try {
                bis = new BufferedInputStream(is);
                bos = new BufferedOutputStream(sout);
                byte[] buff = new byte[2048];
                int bytesRead;
                // Simple read/write loop.
                while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                    bos.write(buff, 0, bytesRead);
                }
            } catch (Exception e) {
                logger.error("导出excel出现异常:", e);
            } finally {
                if (bis != null) {
                    bis.close();
                }
                if (bos != null) {
                    bos.close();
                }
            }

        } catch (Exception e) {
            logger.error("导出excel出现异常:", e);
        }
    }

    private void addCellValueForInteger(XSSFRow row, int indexCell, Integer cellValue){
        XSSFCell cell = row.getCell(indexCell);
        if (null == cell) {
            cell = row.createCell(indexCell);
        }
        cell.setCellValue(cellValue);
    }

    /**
     * 转换状态为“有”或“无”
     * @param row
     * @param indexCell
     * @param cellValue
     */
    private void addCellValueForIntegerStatus(XSSFRow row, int indexCell, Integer cellValue){
        if (cellValue != null && cellValue == 1) {
            addCellValueForString(row, indexCell, "有");
        } else {
            addCellValueForString(row, indexCell, "无");
        }
    }

    private void addCellValueForString(XSSFRow row, int indexCell, String cellValue){
        XSSFCell cell = row.getCell(indexCell);
        if (null == cell) {
            cell = row.createCell(indexCell);
        }
        cell.setCellValue(cellValue);
    }

    @ApiOperation(value = "导入Excel的客户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "文件", required = true, dataType = "file", paramType = "form") ,
            @ApiImplicitParam(name = "userID", value = "登录用户ID", required = true, dataType = "String", paramType = "form")})
    @PostMapping(value = "importCustomerExcel")
    @ResponseBody
    public ReturnBean<List<String>> importCustomerExcel(@RequestParam(value="file") MultipartFile file, String userID){
        ReturnBean<List<String>> returnBean;
        String errorMessage = RightValidator.validateImportCustomerExcelParams(file, userID);
        if (errorMessage.length() > 0) {
            returnBean = new ReturnBean<>(-1, errorMessage);
        } else {
            returnBean = iCustomerService.importCustomerExcel(file, userID);
        }
        return returnBean;
    }

    @ApiOperation(value = "根据角色ID获取功能列表")
    @ApiImplicitParam(name = "roleID", value = "角色ID", required = true, dataType = "String", paramType = "query")
    @RequestMapping(value = "/getRightConfigByRoleID", method = {RequestMethod.GET})
    @ResponseBody
    public ReturnBean<List<FuncList>> getRightConfigByRoleID(String roleID) {
        ReturnBean<List<FuncList>> returnBean;
        String errorMessage = RightValidator.validateGetRightConfigByRoleIDParams(roleID);
        if (errorMessage.length() > 0) {
            returnBean = new ReturnBean<>(-1, errorMessage);
        } else {
            returnBean = iRightConfigService.getRightConfigByRoleID(roleID);
        }
        return returnBean;
    }
    
    /**
     * 从视图中获取指定员工的维护客户
     * 
     * 针对销售
     *
     * @param salesUserID
     * @param customName
     * @param linkMan
     * @param mobile
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "从视图中获取我的客户")
    @ApiImplicitParams({@ApiImplicitParam(name = "salesUserID", value = "员工ID", required = true, dataType = "String", paramType = "form") ,
    		@ApiImplicitParam(name = "customName", value = "客户名称", required = false, dataType = "String", paramType = "form"),
        @ApiImplicitParam(name = "linkMan", value = "联系人", required = false, dataType = "String", paramType = "form"),
        @ApiImplicitParam(name = "mobile", value = "联系电话", required = false, dataType = "String", paramType = "form"),
        @ApiImplicitParam(name = "pageNum", value = "页码（默认第一页）", required = true, dataType = "String", paramType = "form"),
        @ApiImplicitParam(name = "pageSize", value = "每页显示条数（默认10条）", required = true, dataType = "String", paramType = "form")})
    @RequestMapping(value = "/findUserReceivingAddrByPage", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<PageWrapper<UserReceivingAddr>> findUserReceivingAddrByPage(String salesUserID, String customName , String linkMan ,String mobile ,
    			@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10")Integer pageSize) {
    		
        ReturnBean<PageWrapper<UserReceivingAddr>>  returnBean =  iUserReceivingAddrService.findUserReceivingAddrByPage(salesUserID, customName, linkMan, mobile, pageNum, pageSize) ;
        return returnBean;
    }
    
    @ApiOperation(value = "获取订单对应的客户列表")
    @ApiImplicitParams({@ApiImplicitParam(name = "orderType", value = "订单编号", required = true, dataType = "String", paramType = "form") ,
        					@ApiImplicitParam(name = "salesUserID", value = "业务经理ID", required = true, dataType = "String", paramType = "form")})
    @RequestMapping(value = "/getCustomerForOrder", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<List<Customer>> getCustomerForOrder(String orderType, String salesUserID) {
    		String errorMessage = RightValidator.validateGetCustomerForOrder(orderType, salesUserID);
        if (errorMessage.length() > 0) {
        		return new ReturnBean<>(-1, errorMessage);
        }
    		
    		return new ReturnBean<>(ReturnBean.CODE_SUCCESS , "获取订单对应的客户列表成功！" ,iCustomerService.getCustomerForOrder(orderType, salesUserID)) ;
    }
    
    @ApiOperation(value = "获取所有客户列表")
    @ApiImplicitParams({@ApiImplicitParam(name = "customerName", value = "客户名称", required = false, dataType = "String", paramType = "form") ,
    						@ApiImplicitParam(name = "linkMan", value = "联系人", required = false, dataType = "String", paramType = "form") ,
    						@ApiImplicitParam(name = "mobile", value = "手机号", required = false, dataType = "String", paramType = "form") ,
    						@ApiImplicitParam(name = "organizationType", value = "客户类型", required = false, dataType = "String", paramType = "form") ,
    						@ApiImplicitParam(name = "pageNum", value = "页码", required = false, dataType = "Integer", paramType = "form") ,
        					@ApiImplicitParam(name = "pageSize", value = "分页大小", required = false, dataType = "Integer", paramType = "form")})
    @RequestMapping(value = "/getAllCustomer", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<PageWrapper<Customer>> getAllCustomer(String customerName , String linkMan ,String mobile ,String organizationType,
			@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10")Integer pageSize) {
    		
    		return iCustomerService.getAllCustomer(customerName , linkMan ,mobile , organizationType,pageNum,pageSize) ;
    }
    
    /**
     * 删除客户
     * <ul>
     * <li>将组织机构置为无效。</li>
     * <li>如果有仓库也置为无效</li>
     * <li>将组织机构下所有客户都置为无效</li>
     * <li></li>
     * </ul>
     *
     * @param customerID
     */
    @ApiOperation(value = "删除客户", notes = "删除客户")
    @ApiImplicitParam(name = "customerID", value = "客户ID", required = true, dataType = "String", paramType = "form")
    @RequestMapping(value = "/delCustomer", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<Customer> delCustomer(String customerID) {
        if (StringUtils.isEmpty(customerID)) {
            return new ReturnBean<>(1, "客户ID不能为空");
        }
        return iRightService.delCustomer(customerID);
    }
    
    /**
     * 重启客户
     * <ul>
     * <li>将组织机构置为无效。</li>
     * <li>如果有仓库也置为无效</li>
     * <li>将组织机构下所有客户都置为无效</li>
     * <li></li>
     * </ul>
     *
     * @param customerID
     */
    @ApiOperation(value = "重启客户", notes = "重启客户")
    @ApiImplicitParam(name = "customerID", value = "客户ID", required = true, dataType = "String", paramType = "form")
    @RequestMapping(value = "/recoverCustomer", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<Customer> recoverCustomer(String customerID) {
        if (StringUtils.isEmpty(customerID)) {
            return new ReturnBean<>(1, "客户ID不能为空");
        }
        return iRightService.recoverCustomer(customerID);
    }
}
